<template>
  <VScaleScreen width="1920" height="1080">
    <MarsMap :url="configUrl" map-key="test" @onload="marsOnload" />
    <div class="fixed top-[100px] flex flex-col gap-[10px] justify-start">
      <el-button class="ml-[12px]" @click="addWall">添加围墙</el-button>
      <el-button @click="changeColor">修改颜色</el-button>
      <el-button @click="delWall">删除围墙</el-button>
      <el-button @click="showWall">隐藏/显示围墙</el-button>
      <el-button @click="suduWall">调节动效速度</el-button>
      <el-button @click="WallHeight">改变高度</el-button>
      <el-button @click="reverseWallFlow">流动方向</el-button>



    </div>
  </VScaleScreen>

</template>

<script setup lang="ts">
import * as mars3d from "mars3d";
const configUrl = "config/config.json";
import MarsMap from '@/components/mars-map.vue'
import dog from './haShiQi.png'
import VScaleScreen from 'v-scale-screen'


const Cesium = mars3d.Cesium;

let graphicLayer // 矢量图层对象
let geoJsonLayer // 矢量图层对象,用于layer绑定展示

const eventTarget = new mars3d.BaseClass() // 事件机制
// eventTarget.fire("showWebsite", { text: '6666' })
// eventTarget.on("showWebsite", function (event: any) {
//   showLayer.value = event.showHistoryLayer
// })


eventTarget.on("tapLayer", function (event: any) {
  alert('点击了' + event.text)
})


const marsOnload = (map: any) => {
  graphicLayer = new mars3d.layer.GraphicLayer();
  map.addLayer(graphicLayer);

  // 对矢量数据绑定事件
  // 2.在layer上绑定监听事件
  graphicLayer.on(mars3d.EventType.click, function (event: any) {
    console.log("监听layer，单击了矢量对象", event);
    eventTarget.fire("tapLayer", { text: '6666' })

  });
  graphicLayer.on(mars3d.EventType.mouseOver, function (event: any) {
    console.log("监听layer，鼠标移入了矢量对象", event);
  });
  graphicLayer.on(mars3d.EventType.mouseOut, function (event: any) {
    console.log("监听layer，鼠标移出了矢量对象", event);
  });

  // 获取或创建地图实例后
  map.on(mars3d.EventType.drawCreated, function (event) {
    const graphic = event.graphic;
    console.log('绘制完成:', graphic);

    // 判断图形类型
    switch (graphic.type) {
      case 'point':
        console.log('标点结果:', graphic.position);
        break;
      case 'polyline':
        console.log('画线结果:', graphic.positions);
        break;
      case 'polygon':
        console.log('多边形结果:', graphic.positions);
        break;
      case 'rectangle':
        console.log('矩形结果:', graphic.positions);
        break;
      case 'circle':
        console.log('圆形结果:', graphic.position, graphic.radius);
        break;
    }

    // 转换为GeoJSON
    const geojson = graphic.toGeoJSON();
    console.log('GeoJSON格式:', geojson);
  });


  // 监听相机变化，实时获取坐标
  // 方法1：mars3d.EventType.postRender（最高实时性）
  // 方法2：mars3d.EventType.cameraChanged
  map.on(mars3d.EventType.cameraChanged, (event) => {
    const cameraPosition = map.camera.position;

    // 转换为经纬度
    const cartographic = mars3d.LngLatPoint.fromCartesian(cameraPosition);
    console.log("相机实时坐标:", cartographic);
  });



  // 可在图层绑定右键菜单,对所有加到这个图层的矢量数据都生效
  graphicLayer.bindContextMenu([
    {
      text: "删除对象",
      // iconCls: "fa fa-trash-o",
      iconCls: dog,
      callback: function (e: any) {
        const graphic = e.graphic;
        if (graphic) {
          graphicLayer.removeGraphic(graphic);
        }
      },
    },
  ]);
  //  popup
  // 创建矢量数据图层

  map.on(mars3d.EventType.popupOpen, function (event) {
    const container = event.container // popup对应的DOM
    console.log("打开了popup(全局监听)", event)
  })
  map.on(mars3d.EventType.popupClose, function (event) {
    const container = event.container // popup对应的DOM
    console.log("关闭了popup(全局监听)", event)
  })

  // 直接弹toast
  // bindMapDemo(map)
  // bindLayerDemo(map)
  // bindLayerTemplateDemo(map)



  setTimeout(() => {
    // 添加文字
    demoData.addDemoGraphic1(graphicLayer);
    // 添加点
    demoData.addDemoGraphic2(graphicLayer);
    // 添加在线图标
    demoData.addDemoGraphic3(graphicLayer);
    // 添加蓝色贴图
    demoData.addDemoGraphic4(graphicLayer);
    // 添加立方体
    demoData.addDemoGraphic5(graphicLayer);
    // 绿色范围标记
    demoData.addDemoGraphic6(graphicLayer);
    // 圆锥体
    demoData.addDemoGraphic7(graphicLayer);
    // 红色球体
    demoData.addDemoGraphic8(graphicLayer);
    // 添加模型
    // demoData.addDemoGraphic9(graphicLayer);
    // 添加线
    demoData.addDemoGraphic10(graphicLayer);
    // 添加圆管线
    demoData.addDemoGraphic11(graphicLayer);
    // 添加特粗线
    demoData.addDemoGraphic12(graphicLayer);
    // 特效墙
    demoData.addDemoGraphic13(graphicLayer);
    // 矩形范围标记
    demoData.addDemoGraphic14(graphicLayer);
    // 可以做水一类的
    demoData.addDemoGraphic15(graphicLayer);
  }, 5000);



};



const demoData = {
  // 以下为演示代码
  addDemoGraphic1: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.LabelEntity({
      position: new mars3d.LngLatPoint(118.853228, 32.043092, 9659),
      style: {
        text: "添加文字",
        font_size: 25,
        font_family: "楷体",
        color: "red",
        outline: true,
        outlineColor: "#bfbfbf",
        outlineWidth: 2,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        visibleDepth: false,
      },
      attr: { remark: "示例1" },
    });
    graphicLayer.addGraphic(graphic);
  },
  addDemoGraphic2: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.PointEntity({
      position: [116.2, 31.0, 1000],
      style: {
        color: "#ff0000",
        pixelSize: 10,
        outline: true,
        outlineColor: "#ffffff",
        outlineWidth: 2,
      },
      attr: { remark: "示例2" },
    });
    graphicLayer.addGraphic(graphic);
  },

  addDemoGraphic3: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.BillboardEntity({
      name: "贴地图标",
      position: [118.803228, 32.043092, 1000],
      style: {
        // image: "//data.mars3d.cn/img/marker/mark-blue.png",
        image: "./img/cat.png",
        // image: "http://tsconfigserver-cdn.xiangtatech.com/admin/resource/jssgg/jd_1660125955055.png",
        scale: 0.51,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        clampToGround: true,
      },
      attr: { remark: "示例3" },
    });


    graphic.bindPopup(
      function (event) {
        const attr = event.graphic.attr
        return "我是layer上绑定的自定义模版Popup<br />" + attr.type
      },
      {
        template: `<div class="marsBlackPanel animation-spaceInDown">
                        <div style="background-color:red" class="marsBlackPanel-text">{content}</div>
                        <span class="mars3d-popup-close-button closeButton" >×11</span>
                      </div>`,
        horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
        verticalOrigin: Cesium.VerticalOrigin.CENTER
      }
    )

    graphic.on(mars3d.EventType.popupOpen, function (event) {
      const container = event.container // popup对应的DOM
      console.log("图层上打开了popup", container)
    })
    graphic.on(mars3d.EventType.popupClose, function (event) {
      const container = event.container // popup对应的DOM
      console.log("图层上移除了popup", container)
    })


    graphicLayer.addGraphic(graphic);
  },
  addDemoGraphic4: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.PlaneEntity({
      position: new mars3d.LngLatPoint(118.853228, 32.043092, 1000),
      style: {
        plane: new Cesium.Plane(Cesium.Cartesian3.UNIT_Z, 0.0),
        dimensions: new Cesium.Cartesian2(4000.0, 4000.0),
        materialType: mars3d.MaterialType.Image2,
        materialOptions: {
          image: "//data.mars3d.cn/img/textures/poly-rivers.png",
          transparent: true,
        },
      },
      attr: { remark: "示例4" },
    });
    graphicLayer.addGraphic(graphic);
  },
  addDemoGraphic5: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.BoxEntity({
      position: new mars3d.LngLatPoint(118.9032, 32.043092, 1000),
      style: {
        dimensions: new Cesium.Cartesian3(2000.0, 2000.0, 2000.0),
        fill: true,
        color: "#00ffff",
        opacity: 0.9,
        heading: 45,
        roll: 45,
        pitch: 0,
      },
      attr: { remark: "示例5" },
    });
    graphicLayer.addGraphic(graphic);
  },
  addDemoGraphic6: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.CircleEntity({
      position: [118.9532, 32.043092, 1000],
      style: {
        radius: 1800.0,
        color: "#00ff00",
        opacity: 0.3,
        outline: true,
        outlineWidth: 3,
        outlineColor: "#ffffff",
        clampToGround: true,
      },
      popup: "直接传参的popup",
      attr: { remark: "示例6" },
    });
    graphicLayer.addGraphic(graphic);
  },
  addDemoGraphic7: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.CylinderEntity({
      position: [118.688211, 32.072887, 1000],
      style: {
        length: 3000.0,
        topRadius: 0.0,
        bottomRadius: 1300.0,
        color: "#00FFFF",
        opacity: 0.7,
      },
      popup: "直接传参的popup",
      attr: { remark: "示例7" },
    });



    graphicLayer.addGraphic(graphic);
  },
  addDemoGraphic8: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.EllipsoidEntity({
      position: new mars3d.LngLatPoint(118.9032, 32.003092, 1000),
      style: {
        radii: new Cesium.Cartesian3(1500.0, 1500.0, 1500.0),
        color: "rgba(255,0,0,0.5)",
        outline: true,
        outlineColor: "rgba(255,255,255,0.3)",
      },
      attr: { remark: "示例8" },
    });
    graphicLayer.addGraphic(graphic);
  },
  addDemoGraphic9: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.ModelEntity({
      name: "警车",
      position: [118.8532, 32.003092, 1000],
      style: {
        url: "//data.mars3d.cn/gltf/mars/jingche/jingche.gltf",
        scale: 16,
        minimumPixelSize: 100,
      },
      attr: { remark: "示例9" },
    });
    graphicLayer.addGraphic(graphic);
  },
  addDemoGraphic10: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.PolylineEntity({
      positions: [[118.808383, 31.998731, 13.6], [118.819372, 32.015188, 14], [118.832791, 31.999854, 10], [118.832687, 31.999854, 10]],
      style: {
        width: 5,
        color: "#3388ff",
      },
      attr: { remark: "示例10" },
    });
    graphicLayer.addGraphic(graphic); // 还可以另外一种写法: graphic.addTo(graphicLayer)
  },
  addDemoGraphic11: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.PolylineVolumeEntity({
      positions: [[118.75988, 32.014267, 15.2], [118.776251, 31.99429, 34.8], [118.790109, 32.012599, 18.2]],
      style: {
        shape: "pipeline",
        radius: 80,
        color: "#3388ff",
        opacity: 0.9,
      },
      attr: { remark: "示例11" },
    });
    graphicLayer.addGraphic(graphic); // 还可以另外一种写法: graphic.addTo(graphicLayer)
  },
  addDemoGraphic12: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.CorridorEntity({
      positions: [[118.697383, 31.992045, 6.2], [118.73654, 31.999176, 10.1], [118.735989, 32.021281, 10], [118.701274, 32.01289, 6.2], [118.697621, 31.992272, 6.2]],
      style: {
        width: 500,
        color: "#3388ff",
      },
      attr: { remark: "示例12" },
    });
    graphicLayer.addGraphic(graphic); // 还可以另外一种写法: graphic.addTo(graphicLayer)
  },
  addDemoGraphic13: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.WallEntity({
      positions: [[118.746893, 31.952971, 22.3], [118.792171, 31.978738, 18.6], [118.806726, 31.962139, 13], [118.759922, 31.944468, 106.4], [118.748215, 31.953556, 21.2]],
      style: {
        closure: true,
        diffHeight: 500,
        // 动画线材质
        materialType: mars3d.MaterialType.LineFlow,
        materialOptions: {
          image: "//data.mars3d.cn/img/textures/fence.png",
          color: "red",
          speed: 10,
          axisY: true,
        },
      },
      attr: { remark: "示例13" },
    });
    graphicLayer.addGraphic(graphic); // 还可以另外一种写法: graphic.addTo(graphicLayer)
  },
  addDemoGraphic14: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.RectangleEntity({
      positions: [[118.851677, 31.968248, 12.5], [118.900761, 31.940211, 35]],
      style: {
        color: "#3388ff",
        opacity: 0.5,
        outline: true,
        outlineWidth: 3,
        outlineColor: "#ffffff",
      },
      attr: { remark: "示例14" },
    });
    graphicLayer.addGraphic(graphic); // 还可以另外一种写法: graphic.addTo(graphicLayer)
  },
  addDemoGraphic15: (graphicLayer: mars3d.layer.GraphicLayer) => {
    const graphic = new mars3d.graphic.PolygonEntity({
      positions: [[118.942757, 31.968691, 152], [118.942542, 31.937455, 32.2], [118.982497, 31.938045, 28.6], [119.011499, 31.970383, 41.6], [118.942524, 31.968691, 152]],
      style: {
        materialType: mars3d.MaterialType.Water,
        materialOptions: {
          normalMap: "//data.mars3d.cn/img/textures/waterNormals.jpg", // 水正常扰动的法线图
          frequency: 8000.0, // 控制波数的数字。
          animationSpeed: 0.02, // 控制水的动画速度的数字。
          amplitude: 5.0, // 控制水波振幅的数字。
          specularIntensity: 0.8, // 控制镜面反射强度的数字。
          baseWaterColor: "#006ab4", // rgba颜色对象基础颜色的水。#00ffff,#00baff,#006ab4
          blendColor: "#006ab4", // 从水中混合到非水域时使用的rgba颜色对象。
        },
      },
      attr: { remark: "示例15" },
    });
    graphicLayer.addGraphic(graphic); // 还可以另外一种写法: graphic.addTo(graphicLayer)
  },

  addDemoGraphic16: (graphicLayer: mars3d.layer.GraphicLayer) => {
    if (Wall) return
    Wall = new mars3d.graphic.WallEntity({
      positions: [[117.07276, 31.649545, 30.3], [117.075171, 31.651865, 25.8], [117.072981, 31.653915, 29.1], [117.082051, 31.660347, 29.8], [117.08961, 31.65404, 30.4], [117.088562, 31.650563, 25.9], [117.083638, 31.644256, 24.3], [117.080782, 31.64316, 29.4], [117.072749, 31.649653, 27.9]],
      style: {
        closure: true,
        diffHeight: 500,
        // 动画线材质
        materialType: mars3d.MaterialType.LineFlow,
        materialOptions: {
          image: "//data.mars3d.cn/img/textures/fence.png",
          color: "#98fdfe",
          speed: 10,
          axisY: true,
          flowDirection: 1  // 默认自下而上
        },
      },
      attr: { remark: "示例16" },
    });
    graphicLayer.addGraphic(Wall); // 还可以另外一种写法: graphic.addTo(graphicLayer)
  },


};


// 只是为了演示，可以单击详情
function showXQ() {
  const showHistoryLayer = true
  eventTarget.fire("showWebsite", { showHistoryLayer })
}


const removeDemoLayer = () => {
  graphicLayer.clear()

  if (geoJsonLayer) {
    geoJsonLayer.remove(true)
    geoJsonLayer = null
  }
}

// 1.在map地图上绑定Popup单击弹窗
const bindMapDemo = (map) => {
  removeDemoLayer()

  // 关闭弹窗
  map.closePopup()

  // 传入坐标和内容，可以直接任意弹出
  const position = [118.853228, 32.043092, 1521]
  map.openPopup(position, "我是地图上直接弹出的")
}

// 自定义弹出模板
function bindLayerTemplateDemo(map) {
  console.log(map, 'map')
  removeDemoLayer()

  geoJsonLayer = new mars3d.layer.GeoJsonLayer({
    name: "标绘示例数据",
    url: "https://data.mars3d.cn/file/geojson/mars3d-draw.json"
  })

  console.log("标绘示例数据")
  map.addLayer(geoJsonLayer)

  // 在layer上绑定Popup单击弹窗
  geoJsonLayer.bindPopup(
    function (event) {
      const attr = event.graphic.attr
      return "我是layer上绑定的自定义模版Popup<br />" + attr.type
    },
    {
      template: `<div class="marsBlackPanel animation-spaceInDown">
                        <div style="background-color:red" class="marsBlackPanel-text">{content}</div>
                        <span class="mars3d-popup-close-button closeButton" >×11</span>
                      </div>`,
      horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
      verticalOrigin: Cesium.VerticalOrigin.CENTER
    }
  )

  geoJsonLayer.on(mars3d.EventType.popupOpen, function (event) {
    const container = event.container // popup对应的DOM
    console.log("图层上打开了popup", container)
  })
  geoJsonLayer.on(mars3d.EventType.popupClose, function (event) {
    const container = event.container // popup对应的DOM
    console.log("图层上移除了popup", container)
  })
}
// 请求数据自带的模板
const bindLayerDemo = (map) => {
  removeDemoLayer()

  geoJsonLayer = new mars3d.layer.GeoJsonLayer({
    name: "标绘示例数据",
    url: "https://data.mars3d.cn/file/geojson/mars3d-draw.json"
  })
  console.log(geoJsonLayer, 'geoJsonLayer')
  map.addLayer(geoJsonLayer)

  // 在layer上绑定Popup单击弹窗
  geoJsonLayer.bindPopup(async (event) => {
    const attr = event.graphic.attr
    // const newAttr = await mars3d.Util.sendAjax({ url: "http://studio-api.mars3d.cn/api/gap/open/appInfo" })
    const showAttr = {
      ...attr,
      // name: newAttr.data.name,
      // address: newAttr.data.address
      name: '小猫猫',
      address: '南京123456789'
    }
    return mars3d.Util.getTemplateHtml({ title: "标绘示例数据", template: "all", attr: showAttr })
  })


  geoJsonLayer.on(mars3d.EventType.click, function (event) {
    setTimeout(() => {
      const popup = event.graphic.getPopup()
      console.log("测试获取popup", popup)
    }, 1000)
  })

  geoJsonLayer.on(mars3d.EventType.popupOpen, function (event) {
    const container = event.container // popup对应的DOM
    console.log("图层上打开了popup", container)
  })
  geoJsonLayer.on(mars3d.EventType.popupClose, function (event) {
    const container = event.container // popup对应的DOM
    console.log("图层上移除了popup", container)
  })
}




let Wall
const addWall = () => {
  demoData.addDemoGraphic16(graphicLayer);
}

const delWall = () => {
  if (Wall) {
    graphicLayer.removeGraphic(Wall);
    Wall = null
  }
}

const showWall = () => {
  if (Wall) {
    Wall.show = !Wall.show;
  }
}
const suduWall = () => {
  if (Wall) {
    // Wall.setStyle({
    //   speed: 100
    // });
    Wall.style.materialOptions.speed = 200; // 加快动画
    Wall.style = { ...Wall.style }; // 触发更新

  }
}
const WallHeight = () => {
  if (Wall) {
    Wall.style.diffHeight = 1000; // 修改高度
    // Wall.setStyle({
    //   diffHeight: 1000
    // });

    Wall.style.diffHeight = 1000;
    Wall.style = { ...Wall.style }; // 触发更新
  }
}


const reverseWallFlow = () => {
  if (Wall) {
    Wall.setStyle({
      materialOptions: {
        customShader: `
            uniform float speed;
            varying vec2 v_textureCoordinates;
            void main() {
              vec2 reversedUV = vec2(v_textureCoordinates.x, 1.0 - v_textureCoordinates.y);
              gl_FragColor = texture2D(image, reversedUV - vec2(0.0, czm_frameNumber * speed / 100000.0));
            }
          `,
        image: Wall.style.materialOptions.image,
        speed: 10
      }
    });
  }
};

const changeColor = () => {
  // 2. 查找目标围墙（根据 remark 或 id）
  const targetGraphic = graphicLayer.graphics.find(
    graphic => graphic.attr?.remark === "示例16"
  );
  console.log(targetGraphic, 'targetGraphic')
  // 3. 修改颜色
  if (targetGraphic) {
    targetGraphic.setStyle({
      materialOptions: {
        color: "#FF0000", // 修改为红色
      }
    });
    console.log("围墙颜色已更新为红色");
  } else {
    console.error("未找到目标围墙");
  }
}
</script>

<style scoped>
:deep(.mars3d-contextmenu) {
  background: yellow;
}


.mars3d-contextmenu li:hover {
  background: red;
}
</style>
